package com.chen.common.security.config;

import com.chen.root.base.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.LockedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import springfox.documentation.annotations.ApiIgnore;

/**
 * <p>
 * 全局异常处理器结合sentinel 全局异常处理器不能作用在 oauth server https://gitee.com/log4j/pig/issues/I1M2TJ
 * </p>
 *
 * @author long
 * @date 2023-05-14
 */
@Slf4j
@Order(0)
@ApiIgnore
@RestController
@RestControllerAdvice
public class SecurityExceptionHandler {

	/**
	 * AccessDeniedException
	 * @param e the e
	 * @return R
	 */
	@ExceptionHandler(AccessDeniedException.class)
	@ResponseStatus(HttpStatus.FORBIDDEN)
	public R<String> handleAccessDeniedException(AccessDeniedException e) {
		log.error("拒绝授权异常信息 ex={}", e.getMessage());
		return R.failed(null, "权限不足，不允许访问");
	}

	@ExceptionHandler({LockedException.class})
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public R<String> handleLockedException(LockedException exception) {
		log.warn(exception.getMessage());
		return R.failed(null, "您的账号已被冻结，请联系客服！");
	}
}
